var mongoose = require('mongoose');
var fs = require('fs');
var path = require('path');
var config = require('./config');

exports.init = function() {
    var connect = function() {
        var db = config.db;
        mongoose.connect(db.url, db.options);
    };

    connect();

    mongoose.connection.on('error', function(err) {
        console.error(err);

    });

    // Reconnect when closed
    mongoose.connection.on('disconnected', function() {
        connect();
    });

    // Bootstrap models
    var models_path = path.join(config.root, 'models');
    fs.readdirSync(models_path).forEach(function(file) {
        if (~file.indexOf('.js')) require(path.join(models_path ,file));
    });
};